<template>
  <div class="order-confirm">
    <h2>确认订单</h2>
    
    <div class="order-items">
      <h3>商品信息</h3>
      <el-table :data="orderItems" style="width: 100%">
        <el-table-column label="商品信息" min-width="400">
          <template #default="scope">
            <div class="product-info">
              <img :src="scope.row.productImage" class="product-image">
              <div class="product-details">
                <h4>{{ scope.row.productName }}</h4>
                <p class="price">¥{{ scope.row.price }}</p>
                <p class="quantity">x{{ scope.row.quantity }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="小计" width="120">
          <template #default="scope">
            <span class="subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="address-form">
      <h3>收货信息</h3>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="收货人" prop="receiver">
          <el-input v-model="form.receiver" placeholder="请输入收货人姓名" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="收货地址" prop="address">
          <el-input
            v-model="form.address"
            type="textarea"
            :rows="3"
            placeholder="请输入详细收货地址"
          />
        </el-form-item>
      </el-form>
    </div>
    
    <div class="order-footer">
      <div class="total-info">
        <span>总计：</span>
        <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>
      <el-button type="primary" size="large" @click="handleSubmit" :loading="loading">
        提交订单
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const loading = ref(false)
const orderItems = ref([])

const form = ref({
  receiver: '',
  phone: '',
  address: ''
})

const rules = {
  receiver: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { max: 32, message: '收货人姓名不能超过32个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' },
    { max: 255, message: '收货地址不能超过255个字符', trigger: 'blur' }
  ]
}

// 计算总价
const totalPrice = computed(() => {
  return orderItems.value.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)
})

// 获取认证头信息
const getAuthHeaders = () => {
  const token = localStorage.getItem('token')
  return {
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : ''
  }
}

// 获取购物车选中商品
const fetchSelectedItems = async () => {
  try {
    const response = await fetch('/api/cart/items', {
      headers: getAuthHeaders()
    })
    
    if (!response.ok) {
      throw new Error('获取购物车列表失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || '获取购物车列表失败')
    }
    
    orderItems.value = data.data.filter(item => item.selected === 1)
    
    if (orderItems.value.length === 0) {
      ElMessage.warning('请先选择要购买的商品')
      router.push('/cart')
    }
    
  } catch (error) {
    console.error('获取购物车列表错误:', error)
    ElMessage.error(error.message || '获取购物车列表失败，请稍后再试')
    router.push('/cart')
  }
}

// 提交订单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }
    
    loading.value = true
    
    // 构造符合后端要求的请求体
    const requestBody = {
      address: form.value.address,
      receiver: form.value.receiver,
      phone: form.value.phone,
      orderItems: orderItems.value.map(item => ({
        productId: item.productId,
        quantity: item.quantity
      }))
    }
    
    console.log('提交订单数据:', requestBody)
    
    const response = await fetch('/api/orders', {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(requestBody)
    })
    
    if (!response.ok) {
      throw new Error('创建订单失败')
    }
    
    const data = await response.json()
    
    if (data.code !== 200) {
      throw new Error(data.message || '创建订单失败')
    }
    
    ElMessage.success('订单创建成功')
    router.push('/orders')
    
  } catch (error) {
    console.error('创建订单错误:', error)
    // 如果是表单验证错误，不需要显示错误消息，因为 Element Plus 会自动显示
    if (!error.message) {
      return
    }
    ElMessage.error(error.message || '创建订单失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchSelectedItems()
})
</script>

<style scoped>
.order-confirm {
  padding: 20px;
  min-height: 100%;
  position: relative;
  padding-bottom: 100px; /* 为底部固定的订单栏留出空间 */
}

.order-items,
.address-form {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 20px;
}

.product-details h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
}

.price {
  color: #f56c6c;
  margin: 0;
}

.quantity {
  color: #666;
  margin: 5px 0 0 0;
}

.subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.order-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  z-index: 100; /* 确保底部栏在最上层 */
}

.total-info {
  font-size: 16px;
}

.total-info .price {
  font-size: 24px;
  font-weight: bold;
}
</style> 